package codingforgreat.lchot150;

public class Lc029 {
    //1.位运算实现加法
    public static int add(int a,int b){
        int sum = a;
        while (b != 0){
            sum = a ^ b;
            b = (a & b) << 1;
            a = sum;
        }
        return sum;
    }
    //2.减法
    public static int minus(int a,int b){
        //1.a - b = a + (- b) => a + ( ~ b + 1)
        return add(a,add(~b,1));
    }
    //3.乘法
    public static int multiply(int a,int b){
        int res = 0;
        while(b != 0){
            if((b & 1) == 1){
                res = add(res,a);
            }
            a <<= 1;
            b >>>= 1;
        }
        return res;
    }
    //取-
    public  int negNum(int n) {
        return add(~n, 1);
    }
    public boolean isNeg(int n){
        return n < 0;
    }
    public int divide(int dividend, int divisor) {
       if(dividend == Integer.MIN_VALUE && divisor == Integer.MIN_VALUE){
           return 1;
       }else
       if(divisor == Integer.MIN_VALUE){
           return 0;
       }else if(dividend == Integer.MIN_VALUE){
           if(divisor == negNum(1)){
               return Integer.MAX_VALUE;
           }else{
               //-( a - 1 ) / b
                int c = div(add(dividend,1),divisor);
               //c + ((a -(c * b)	) / b)
               return add(c,div(minus(dividend,multiply(c,divisor)),divisor));
           }

       }else{
           return div(dividend,divisor);
       }
    }
    public int div(int a,int b){
        int x = isNeg(a) ? negNum(a) : a;
        int y = isNeg(b) ? negNum(b) : b;
        int res = 0;
        for(int i = 30;i >= 0; i--){
            if((x >> i) >=  y){
            res |= (1 << i);
            x = minus(x,y << i);
            }
        }
        return isNeg(a) ^ isNeg(b) ? negNum(res) : res;
    }

    public static void main(String[] args) {
        System.out.println(add(50,49));
        System.out.println(minus(30,19));
        System.out.println(multiply(-3,9));
    }
}
